package com.pdsu.alumni.mail;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdsu.alumni.config.RabbitMQConfig;
import com.pdsu.alumni.pojo.Mail;
import com.pdsu.alumni.pojo.MqLog;
import com.pdsu.alumni.service.IMqLogService;
import com.pdsu.alumni.util.Constant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program: alumni
 * @description: 消息接收者类
 * @author: Acerola
 * @create: 2021-12-13 23:48
 **/
@Component
@Slf4j
public class ConsumerMailService {

    @Autowired
    private SendMailUtil sendMailUtil;
    @Autowired
    private IMqLogService mqLogService;

    @RabbitListener(queues = RabbitMQConfig.MAIL_QUEUE_NAME)
    public void consume(Message message, Channel channel) throws IOException {
        //将消息转化为对象
        String str = new String(message.getBody());
        Mail mail = JSON.parseObject(str, Mail.class);
        log.info("收到消息: {}", mail.toString());
        //消费幂等性,如果出现已经消费,不用再重复发送邮件
        String mqId = mail.getMsgId();
        QueryWrapper<MqLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("msg_id", mqId);
        MqLog mqLog = mqLogService.getOne(queryWrapper);
        if (mqLog == null || mqLog.getStatus().equals(Constant.RabbitMQ_CONSUME_SUCCESS)) {
            log.info("重复消费,mqId:{}", mqId);
            return;
        }
        MessageProperties properties = message.getMessageProperties();
        long tag = properties.getDeliveryTag();

        boolean success = sendMailUtil.send(mail);
        if (success) {
            mqLog.setStatus(Constant.RabbitMQ_CONSUME_SUCCESS);
            System.out.println("目前消息的状态是" + mqLog.getStatus());
            mqLogService.updateByMqId(mqId, Constant.RabbitMQ_CONSUME_SUCCESS);
            channel.basicAck(tag, false);// 消费确认
            System.out.println("消息已消费");
        } else {
            System.out.println("消息发送失败");
            channel.basicNack(tag, false, true);
        }
    }
}